class HubWidget < ActiveRecord::Base
  belongs_to :hub
  belongs_to :widget
  has_many :widget_datas
  
  acts_as_list :scope => :hub_id
  
  validates_presence_of :hub_id
  validates_presence_of :widget_id
  validates_presence_of :size
  validates_numericality_of :size
  
  def root_object
    DataSystem.new(self)
  end
  
  def render_view(options = {:timeout => 1.0})
    wv = widget.code_files.widget_view
    if wv
      wv.render_view(self, options)
    else
      "<p>Widget has no view file.</p>"
    end
  end
  
  def run_background(options = {:timeout => 10.0})
    bg = widget.code_files.background
    if bg
      bg.run(self.root_object, options)
    end    
  end
  
  def invalidate_cache!
    HubWidget.update_all("cache = NULL", "id = #{self.id}")
  end
end
